package com.spica.spicaschool.utils

import android.content.Context
import com.tencent.cos.xml.CosXmlService
import com.tencent.cos.xml.CosXmlServiceConfig
import com.tencent.qcloud.core.auth.QCloudCredentialProvider
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider


/**
 * 腾讯COS工具类
 */
object CosServiceFactory {
    private const val defaultRegion = "ap-nanjing"

    private val cosXmlServiceMap: MutableMap<String, CosXmlService> = HashMap()

    private fun getCosXmlService(
        context: Context, region: String, secretId: String,
        secretKey: String, refresh: Boolean
    ): CosXmlService {
        if (refresh) {
            cosXmlServiceMap.remove(region)
        }
        var cosXmlService = cosXmlServiceMap[region]
        if (cosXmlService == null) {
            val cosXmlServiceConfig = getCosXmlServiceConfig(region)
            val qCloudCredentialProvider = getCredentialProviderWithIdAndKey(secretId, secretKey)
            cosXmlService = CosXmlService(context, cosXmlServiceConfig, qCloudCredentialProvider)
            cosXmlServiceMap[region] = cosXmlService
        }
        return cosXmlService
    }

    fun getCosXmlService(
        context: Context,
        secretId: String,
        secretKey: String,
        refresh: Boolean
    ): CosXmlService {
        return getCosXmlService(context, defaultRegion, secretId, secretKey, refresh)
    }

    /**
     * 获取配置类
     */
    private fun getCosXmlServiceConfig(region: String): CosXmlServiceConfig {
        return CosXmlServiceConfig.Builder()
            .setRegion(region)
            .setDebuggable(true)
            .isHttps(true)
            .builder()
    }

    /**
     * 获取QCloudCredentialProvider对象，来给 SDK 提供临时密钥
     * @parma secretId 永久密钥 secretId
     * @param secretKey 永久密钥 secretKey
     */
    private fun getCredentialProviderWithIdAndKey(
        secretId: String,
        secretKey: String
    ): QCloudCredentialProvider {
        /**
         * 注意！注意！注意！
         * 由于该方式会存在泄漏密钥的风险，我们强烈不推荐您使用这种方式，建议您仅在安全的环境下临时测试时使用.
         * 建议采用"通过临时秘钥进行授权"，请参考：https://cloud.tencent.com/document/product/436/12159#.E5.88.9D.E5.A7.8B.E5.8C.96.E6.9C.8D.E5.8A.A1
         */
        return ShortTimeCredentialProvider(secretId, secretKey, 300)
    }
}